var orderPayApp = angular.module("orderPayApp", []);
orderPayApp.controller("orderPayController", function($scope, $rootScope, $q, $http, scCodeService, $location, $state, Popup, $stateParams) {
    //订单价格数据处理，从2处理成2.00格式
    $scope.intToFloat = function(num) {
            num = Math.round(num * 100) / 100;
            var obj = num.toString().split(".");
            if (obj.length == 1) {
                num = num + '.00';
            } else {
                if (obj[1].length == 1) {
                    num = num + '0';
                }
            }
            return num;
            
        }
        //订单数据显示处理方法
    $scope.orderShow = function(data) {
            //判断订单状态，未支付则停留在此页，已支付则跳转至订单完成界面
            if (data.status == "7") {
                $location.path("/evaluation/" + $scope.orderNo);
            }
            //计算充电费和服务费，优惠
            $scope.chargePrice = 0;
            $scope.servicePrice = 0;
            $scope.discountPrice = 0;
            $scope.reservationPrice=0;
            $scope.countPrice = 0;
            $scope.chargeList = data.orderDetails;
            
            angular.forEach($scope.chargeList, function(data, index, array) {
                if (array[index].serviceNo == "100002") {
                    
                    $scope.chargePrice = parseFloat($scope.chargePrice + array[index].totalPrice);
                } else if (array[index].serviceNo == "100001") {
                    
                    $scope.servicePrice = parseFloat($scope.servicePrice + array[index].totalPrice);
                } else if (array[index].serviceNo == "100003") {
                    
                    $scope.reservationPrice = parseFloat($scope.servicePrice + array[index].totalPrice);
                }
                $scope.countPrice = parseFloat($scope.countPrice) + parseFloat(array[index].totalPrice);
                $scope.discountPrice = parseFloat($scope.discountPrice) + parseFloat(array[index].totalPrice - array[index].realTotalPrice);
            });
            $scope.reservationPrice= $scope.intToFloat($scope.reservationPrice);
            $scope.chargePrice = $scope.intToFloat($scope.chargePrice);
            $scope.servicePrice = $scope.intToFloat($scope.servicePrice);
            $scope.countPrice = $scope.intToFloat($scope.countPrice);
            //判断优惠金额是否有值，有则显示，无则隐藏
            $scope.hasDiscount = false;
            if ($scope.discountPrice && $scope.discountPrice > 0) {
                $scope.hasDiscount = true;
                $scope.discountPrice = $scope.intToFloat($scope.discountPrice);
            }
            
            //将订单数据存储到本地localStorage里
            var ls = localStorage;
             //0
            ls.removeItem('payDetail');
             //清除存入数据
            ls.setItem('userinfo', JSON.stringify($scope.userinfo));
            ls.setItem('payDetail', JSON.stringify(data));
            ////显示存入数据
        }
        //获取路由上的订单id调用接口获取订单详情
    $rootScope.getOrderDetailByOrderNo = function() {
        var deferred = $q.defer();
        //获取路由上获取订单id
        if ($stateParams.orderNo) {
            $scope.orderNo = $stateParams.orderNo;
        }
        //根据订单号查询订单详细
        var postData = {
            orderNo: $scope.orderNo
        }
        scCodeService.getOrderDetail(postData).then(function(data) {
            
            if (data.code == "200") {
                if (data.data) {
                    $scope.order = data.data;
                    
                    //调用订单显示数据处理方法
                    deferred.resolve($scope.order)

                }
            }
        })
        return deferred.promise;
    }
    // 进入支付页执行的方法
    $rootScope.getOrderDetailByOrderNo().then(function(data) {
        $scope.orderShow(data);
    });
    //获取支付接口参数
    $scope.getPayParams = function() {
            $scope.loadingToastSet("支付请求中...");
            var openId = localStorage.getItem("openId");
            //获取支付接口参数
            var postData = {
                orderNo: $scope.orderNo,
                payType: "weixin",
                appId: mainConfig.source,
                body: '电庄股份-电动汽车充电服务',
                openId: openId
            }
            scCodeService.getPayParams(postData).then(function(data) {
                /*var result = JSON.stringify(data);
            	alert(result);*/
                
                $scope.loadingToastHide();
                if (data.code == "200") {
                    if (data.data) {
                        $scope.wxParams = data.data.bizData;
                        if ($scope.wxParams.returnCode == "SUCCESS") {
                             //显示存入数据
                            $scope.callpay(); //调用支付插件
                        } else {
                            Popup.notice($scope.wxParams.msg, 3000, function() {
                                
                            });
                        }

                    }
                } else {
                    Popup.notice('请求失败', 3000, function() {
                        
                    });
                }
            })
        }
        //生成32位随机数，微信支付参数用
    $scope.generateMixed = function() {
            $scope.chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
            var charsres = '';
            for (var i = 0; i < 32; i++) {
                var id = Math.ceil(Math.random() * 35);
                charsres += $scope.chars[id];
            }
            return charsres;
        }
        //调用微信JS api 支付
    $scope.jsApiCall = function() {
            //传入参数，调用微信支付插件
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                    "appId": $scope.wxParams.appId, //公众号名称，由商户传入 ,$scope.wxParams.appId,//    
                    "timeStamp": $scope.wxParams.timeStamp, //时间戳，自1970年以来的秒数     $scope.wxParams.timeStamp,//
                    "nonceStr": $scope.wxParams.nonceStr, //随机串     $scope.wxParams.nonceStr,//
                    "package": $scope.wxParams.packageStr, // $scope.wxParams.package,//
                    "signType": "MD5",
                    "total_fee": "80", //微信签名方式：     
                    "paySign": $scope.wxParams.paySign //微信签名 $scope.wxParams.paySign,//
                },
                function(res) {
                    WeixinJSBridge.log(res.err_msg);
                    
                    //alert(res.err_code+res.err_desc+res.err_msg);
                    //alert(res.err_msg);
                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                        //成功回调
                        //$location.path("/myOrder");
                        //alert("ok");
                        window.location.href = mainConfig.hostUrl + "index.html?#/evaluation/"+$scope.orderNo;
                    } else {
                        Popup.notice(res.err_msg, 3000, function() {

                        });
                    }
                }
            );
        }
        //检测浏览器是否支持微信JS-SDK
    $scope.callpay = function() {
        if (typeof WeixinJSBridge == "undefined") {
            if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', $scope.jsApiCall(), false);
            } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', $scope.jsApiCall());
                document.attachEvent('onWeixinJSBridgeReady', $scope.jsApiCall());
            }
        } else {
            $scope.jsApiCall();
        }
    }

})



//评价页控制器
orderPayApp.controller('evaluate', function($scope, $rootScope,$q, $http, scCodeService, $location, $state, Popup, $stateParams) {
    $scope.star = 0;
    $scope.wordsEvl;
    $scope.couldEvl = false;
    $scope.lables = "";
    $scope.hasEvalutaion=true;
    $scope.isWechatPay=true;
    $scope.isNotPay=false;
    //獲取用戶id
    var userId = localStorage.getItem("userId");
    $scope.evalu = function(index) {
        $scope.star = index;
        $scope.starDesc = (globalFun.starDesc)[index - 1];
        $scope.couldEvl = true;
    };
    $scope.market = function(index) {
        for (var i = 1; i < 5; i++) {
            var change = "change" + i;
            var lable = "lable" + i;
            if (index == i) {
                if ($scope[change] == index) {
                    $scope[change] = "";
                    $scope[lable] = ""
                } else {
                    $scope[lable] = globalFun.lables[index - 1];
                    $scope[change] = index;
                }
                $scope.lables += "#" + $scope[lable];
                break;
            }
        }
    };
    $scope.submitSug = function() {
        $scope.orderNo = $stateParams.orderNo;
        var postData = {
            orderNo: $scope.orderNo,
            lables: $scope.lables,
            grade: $scope.star,
            evaluate: $scope.wordsEvl,
            userId:userId
        };
        //alert(JSON.stringify(postData));
        if ($scope.couldEvl == true) {
            scCodeService.orderAttach(postData).then(function(data) {
                //alert(JSON.stringify(data));
                if (data.code == "200") {
                    $scope.toastSet({
                        content: "评价成功"
                    });
                    window.location.href=mainConfig.hostUrl+"index.html#/orderDetail/" + $scope.orderNo;
                }
            });
        }
    };
    // $scope.focus=function();
    $scope.wordsCtr = function() {
        if ($scope.wordsEvl.length > 300) {
            $scope.wordsEvl = $scope.wordsEvl.substr(0, 300);
            $scope.toastSet({
                content: "输入超长，请输入300个中文以内的意见或建议。"
            });
        }
    };


// 测试用，线上可删除
    $rootScope.getOrderDetailByOrderNo = function() {
        var deferred = $q.defer();
        //获取路由上获取订单id
        if ($stateParams.orderNo) {
            $scope.orderNo = $stateParams.orderNo;
        }
        //根据订单号查询订单详细
        var postData = {
            orderNo: $scope.orderNo
        }
        scCodeService.getOrderDetail(postData).then(function(data) {
            
            if (data.code == "200"){
                if (data.data) {
                    $scope.order = data.data;
                    if($scope.order.grade!=undefined && $scope.order.grade!=""){
                        $scope.hasEvalutaion=false; //如果订单已评价则不显示评价功能
                    }
                    if (data.caculatedTotalPrice == "0.00") {
                        $scope.isWechatPay=false;
                        $scope.isNotPay=true;
                    }
                    
                    //调用订单显示数据处理方法
                    deferred.resolve($scope.order)

                }
            }
        })
        return deferred.promise;
    };
    // 进入评价页执行的方法
    $rootScope.getOrderDetailByOrderNo();
})
